#! /usr/bin/env python
# coding=utf-8

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.db import connection
from django.template import RequestContext
import sys,settings,re,datetime,traceback
if '..' not in sys.path:
    sys.path.append('..')
from common.taobao import *
from common.urlUtil import *

class LoginFilter:
    def process_request(self, request):
        traceId = request.REQUEST.get('traceId')
        if traceId:
            request.traceId = traceId
        else:
            request.traceId = ''
        path = request.path.lower()
        request.basePath = request.build_absolute_uri('/')[:-1]
        request.PUBLISH_FLAG = settings.PUBLISH_FLAG
        if path in settings.NOT_FILTER_PATH:
            return
        for item in settings.NOT_FILTER_END_PATH:
            if path.endswith(item):
                return

    def process_response(self, request, response):
        closeThreadLocalMongoDB()
        return response
        
    def process_exception(self, request, exception):
        closeThreadLocalMongoDB()

class PermissionFilter:
    def process_request(self, request):#session id, deal path
        path = request.path.lower()
        if path in settings.NOT_PERMISSION_PATH:
            return
        for item in settings.NOT_PERMISSION_END_PATH:
            if path.endswith(item):
                return
        if path.find('/hjq/') > -1:
            return

        if not request.session.get('userId'):
            return

        if path != '/':
            path = self.dealPath(path)

        appKey = getAppKeyFromRequest(request)
        if RoleService().judgePathPermission(int(request.session['userId']), appKey, path):
            return

        return HttpResponseRedirect('/permissionRequired')
        
    def dealPath(self, path):
        result = path.replace('/create/', '/')
        result = re.sub(r'/\d+/edit/', '/', result)
        result = re.sub(r'/\d+/delete/', '/', result)
        result = re.sub(r'/delete/', '/', result)
        result = re.sub(r'/\d+/', '/', result)
        return result

    def process_exception(self, request, exception):
        if exception.__class__.__name__ == 'TopInvalidSessionException':
            return HttpResponseRedirect('/topSessionTimeout')
        if exception.__class__.__name__ == 'UserWithoutShopException':
            return render_to_response('userWithoutShop.html', {}, context_instance=RequestContext(request))
        settings.logger.error(traceback.format_exc())

class PermissionRepository():
    def _getMenu1(self):
        mongoDB = getThreadLocalMongoDB()['mongoDB']
        #li = mongoDB.Menu.find({'type': 0, '$where': 'this.level.length == 3'}).sort('level', pymongo.ASCENDING)
        li = mongoDB.Menu.find({'type': 0, 'level': re.compile(r'^...$')}).sort('level', pymongo.ASCENDING)
        return [item for item in li]

    def _getMenu(self, level):
        mongoDB = getThreadLocalMongoDB()['mongoDB']
        li = mongoDB.Menu.find({'type': 0, 'level': re.compile('^%s...$' % (level))}).sort('level', pymongo.ASCENDING)
        return [item for item in li]

    def getFullMenu(self, path):
        menu1 = self._getMenu1()
        currentMenu3 = None
        if path in ('/', '/index/'):
            currentMenu1 = menu1[0]
            menu2 = self._getMenu(currentMenu1['level'])
            for item in menu2:
                item['children'] = self._getMenu(item['level'])
            if len(menu2) > 0 and menu2[0].get('children'):
                currentMenu3 = menu2[0]['children'][0]
        else:
            #currentMenu = Permission.objects.get(url=path)
            mongoDB = getThreadLocalMongoDB()['mongoDB']
            currentMenu = mongoDB.Menu.find_one({'url': path})
            if currentMenu['type'] == 1:
                currentMenu = mongoDB.Menu.find_one({'level': currentMenu['level'][:-3]})
                #currentMenu = Permission.objects.get(appKey=appKey, level=currentMenu.level[:-3])
            if len(currentMenu['level']) / 3 == 1:
                currentMenu1 = currentMenu
                menu2 = self._getMenu(currentMenu1['level'])
                for item in menu2:
                    item['children'] = self._getMenu(item['level'])
                if len(menu2) > 0 and menu2[0].get('children'):
                    currentMenu3 = menu2[0]['children'][0]
            else:
                #currentMenu1 = Permission.objects.get(appKey=appKey, level=currentMenu.level[:3], type=0)
                currentMenu1 = mongoDB.Menu.find_one({'level': currentMenu['level'][:3], 'type': 0})
                menu2 = self._getMenu(currentMenu1['level'])
                for item in menu2:
                    item['children'] = self._getMenu(item['level'])
                currentMenu3 = currentMenu
        
        result = {}
        result['menu1'] = menu1
        result['menu2'] = menu2
        for item in menu1:
            if item['id'] == currentMenu1['id']:
                item['isCurrent'] = 'True'
                break
        if currentMenu3:
            flag = False
            for item in menu2:
                for innerItem in item['children']:
                    if innerItem['id'] == currentMenu3['id']:
                        innerItem['isCurrent'] = 'True'
                        flag = True
                        break
                if flag:
                    break
    
        return result

def getMenuCommon(request):
    path = request.path
    if path != '/':
        path = PermissionFilter().dealPath(path)

    request.menu = PermissionRepository().getFullMenu(path)

def getMenu(view_func):
    def _wrap_getMenu(request, *param1, **param2):
        getMenuCommon(request)
            
        return view_func(request, *param1, **param2)
    return _wrap_getMenu

def getMenuIfNotPost(view_func):
    def _wrap_getMenu(request, *param1, **param2):
        if request.method == 'GET':
            getMenuCommon(request)
            
        return view_func(request, *param1, **param2)
    return _wrap_getMenu

class LoginAdapter:
    def process_request(self, request):
#        user = SysUser.objects.get(nick='sandbox_c_1')
#        user = SysUser.objects.get(nick='hjq20021984')
#        user = SysUser.objects.get(nick='initUserNick')
#        request.session['userId'] = user.id
        request.session['userId'] = 11
#        request.session['userId'] = 114
        request.session['resStruct'] = {'top_session': '411191106b3b79519aIQhBzoROcee355094c3a7f2d223061759782691',
'url': 'http://127.0.0.1:8000',
'top_sign': 'TOeihQub//33GUCZjlUDeg==',
'top_appkey': '12130139',
'app_key': '12130139',#冗余top_appkey的值
'topParameter': {
    'visitor_nick': 'sandbox_c_1',
    'view_width': '0',
    'visitor_id': '175978269',
    'ts': '1284688966511',
    'view_mode': 'full',
    'iframe': '1'},
'top_parameters':'aWZyYW1lPTEmdHM9MTI4NDY4ODk2NjUxMSZ2aWV3X21vZGU9ZnVsbCZ2aWV3X3dpZHRoPTAmdmlzaXRvcl9pZD0xNzU5NzgyNjkmdmlzaXRvcl9uaWNrPXNhbmRib3hfY18x'}
#        request.session['userId'] = 256
#        request.session['resStruct'] = {'app_key': settings.TAOBAO_APP_KEY_CHAT}
#        request.session['resStruct'] = {'app_key': settings.TAOBAO_APP_KEY_FRONT}
#        request.session['resStruct'] = {'app_key': settings.TAOBAO_APP_KEY_BACK}
#        if request.session.get('resStruct'):
#            del request.session['resStruct']
        path = request.path.lower()
        for item in settings.NOT_FILTER_END_PATH:
            if path.endswith(item):
                return
#       UserLogin().dealLogin(request)
    
if __name__ == '__main__':
    pass
